package com.lzy.webapi.facade;

import com.lzy.base.apis.SysUserAdminServiceApi;
import com.lzy.base.apis.SysUserRoleServiceApi;
import com.lzy.base.dtos.SysUserAdminDto;
import com.lzy.base.dtos.SysUserRoleDto;
import com.lzy.common.apis.ShopServiceApi;
import com.lzy.common.apis.StoreServiceApi;
import com.lzy.common.constants.BusinessType;
import com.lzy.common.dtos.ShopDto;
import com.lzy.common.dtos.ShopSaveDto;
import com.lzy.common.dtos.StoreDto;
import com.lzy.common.dtos.SysShopInDto;
import com.lzy.framework.core.ensure.Ensure;
import com.lzy.framework.core.utils.DozerUtils;
import com.lzy.framework.tools.date.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 卡券宝销售商店铺相关
 */

@Component
public class ShopServiceFacade {

    @Autowired
    private ShopServiceApi shopService;

    @Autowired
    private StoreServiceApi storeService;

    @Resource
    private SysUserAdminServiceFacade sysUserAdminServiceFacade;

    @Autowired
    private SysUserRoleServiceApi sysUserRoleService;


    /**
     * 商户新增公共方法
     *
     * @param request        modules      商户类型
     *                       detailImages 图文详情（非必填）
     *                       <p>
     *                       //关联品牌
     *                       categoryId   商户类别（shop_category）
     *                       storeName    店铺名称
     *                       brands
     *                       <p>
     *                       //证件上传
     *                       证件上传地址判断 需要上传的证件传证件地址即可{
     *                       licenceUrl   营业执照
     *                       regristUrl   税务登记证
     *                       organizeUrl  组织机构代码
     *                       IDUrlObverse 身份证正面照
     *                       IDUrlBack    身份证反面
     *                       driverUrl    驾驶证
     *                       }
     *                       <p>
     *                       //企业信息新增
     *                       name         企业名称
     *                       area         企业所属城市
     *                       linkMan      联系人
     *                       contact      联系电话
     *                       address      详细地址
     *                       tel          企业电话
     *                       //审核所需信息
     *                       licenseUrl   商户对应的数据，详情页路径
     *                       licenseCode  商户对应的按钮，资源编码
     *                       //角色关联
     *                       userId       操作用户id（获取不到时给个1）
     *                       curUserStr   用户信息字符串数组
     *
     * @return              Long userId
     */
    public Long saveShop(ShopSaveDto request) {
        Ensure.that(request).isNotNull("04000001");
        //没有店铺则新增
        StoreDto storeDto = enableContact(request);
        Long shopId;
        Long userId = 0L;
        if (storeDto==null){
            String modules = request.getModules();
            Ensure.that(modules).isNotNull("04000021");
            //添加商户
            SysUserAdminDto sysUserAdminDto = sysUserAdminServiceFacade.selectByPhone(request.getAccount());
            if (sysUserAdminDto == null){
                request.setStatus(BusinessType.StatusEnum.ENABLED.getCode());//启用
                request.setCreateUser(BusinessType.SYS_USER_ADMIN_ID);
                String merchants = DateUtils.getDateRandom();
                SysShopInDto sysShopInDto = new SysShopInDto();
                sysShopInDto.setPhone(request.getContact());
                sysShopInDto.setMerchants(merchants);
                sysShopInDto.setShopAppId(Long.valueOf(request.getShopAppId()));
                shopId = shopService.insertShop(DozerUtils.map(request, ShopDto.class));
                Ensure.that(shopId).isGt(0, "04000022");
                //用户商户的店铺新增  (获取storeId ,同时赋予角色权限)
                if (request.getCategoryId().equals(BusinessType.ShopType.SALE_MAN.getCode())) {
                    /*第二步 ： 创建用户(获取userId) 已存在则不新增*/
                    SysUserAdminDto sysUserAdmin = new SysUserAdminDto();
                    sysUserAdmin.setShopId(shopId);
                    sysUserAdmin.setLoginName(request.getContact());
                    sysUserAdmin.setPhone(request.getContact());
                    sysUserAdmin.setRealName(request.getName());
                    sysUserAdmin.setState(BusinessType.StatusEnum.ENABLED.getCode());
                    sysUserAdmin.setCreateUser(request.getCreateUser());
                    sysUserAdmin.setIDNumber(request.getIdCardNo());
                    userId = sysUserAdminServiceFacade.insert(sysUserAdmin, null, null);

                    SysUserRoleDto sysUserRoleDto = new SysUserRoleDto();
                    sysUserRoleDto.setUserId(userId);
                    sysUserRoleDto.setRoleId(BusinessType.RoleType.SELLERS.getCode());
                    SysUserRoleDto dto = sysUserRoleService.selectByUserRole(sysUserRoleDto);
                    if (dto == null){
                        Ensure.that(sysUserRoleService.addUserRole(sysUserRoleDto)).isTrue("04000023");
                    }
                }
            } else {
                shopId = sysUserAdminDto.getShopId();
            }
            StoreDto storePersonal = new StoreDto();
            storePersonal.setName(request.getContact());
            storePersonal.setShopId(shopId);
            storePersonal.setRemark(request.getRemark());
            storePersonal.setCategoryId(request.getCategoryId());
            storePersonal.setLegalName(request.getLinkMan());
            storePersonal.setLegalContact(request.getContact());
            Long storeId = storeService.insertSelective(storePersonal);
            Ensure.that(storeId).isGt(0, "04000024");
        }
        return userId;
    }

    private StoreDto enableContact(ShopSaveDto shopSaveDto) {
        Ensure.that(shopSaveDto).isNotNull("04000001");
        Ensure.that(shopSaveDto.getContact()).isNotNull("04000001");
        StoreDto store = new StoreDto();
        store.setLegalContact(shopSaveDto.getContact());
        store.setCategoryId(BusinessType.ShopType.SALE_MAN.getCode());
        StoreDto storeDto = storeService.findStoreByContactAndCategory(store);
        return storeDto;
    }

}
